package com.llxz.blog.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class IpUtil {
    public static String getAddressResult(String ip) {
        // 创建默认http连接
        HttpClient client = HttpClients.createDefault();
        // 创建一个post请求
        HttpPost post = new HttpPost("http://api.map.baidu.com/location/ip");
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        // 传递的参数
        paramList.add(new BasicNameValuePair("ak", "urKkLc6tDF27Aua9rmUXza7l9UWxXsei"));
        paramList.add(new BasicNameValuePair("ip", ip));
        String address = "";
        try {
            // 把参转码后放入请求实体中
            HttpEntity entitya = new UrlEncodedFormEntity(paramList, "utf-8");
            post.setEntity(entitya);// 把请求实体放post请求中
            // 用http连接去执行get请求并且获得http响应
            HttpResponse response = client.execute(post);
            // 从response中取到响应实体
            HttpEntity entity = response.getEntity();
            // 把响应实体转成文本
            String str = EntityUtils.toString(entity);

            // 分隔解析
            if(str.length() >0) {
                int index = str.indexOf("province");
                int index2 = str.indexOf("city");
                int index3 = str.indexOf("district");
                String province = str.substring(index+11, index2-3);
                String city = str.substring(index2+7, index3-3);
                address = UnicodeUtil.decodeUnicode(province);
            }
        } catch (Exception e) {
            //System.out.println(e);
            return "未知";
        }
        System.out.println("address: "+address);
        return address;
    }


}
